﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using JetBlack.Runtime.InteropServices;
using Microsoft.Office.Interop;
using Microsoft.Win32;

namespace JetBlack.FeedBus.ExcelAddin
{
    [Guid("AD10238A-C9BF-4502-AC0C-A438CA2FD9C2")]
    [ComVisible(false)]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface IComAddinImpl
    {
        [DispId(1)]
        object TopicSubscribe(string feed, string topic, string fieldName, [Optional] object defaultValue, [Optional] object host, [Optional] object port);
    }

    [Guid("5577700D-9AA0-4392-A048-D8020EF29BEC")]
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.AutoDual)]
    [ProgId(ComAddinImpl.ProgId)]
    public class ComAddinImpl : Extensibility.IDTExtensibility2, IComAddinImpl
    {
        public const string ProgId = "JetBlack.FeedBusComAddin";

        private static Microsoft.Office.Interop.Excel.Application Application;
        private static Microsoft.Office.Core.COMAddIn COMAddIn;

        public ComAddinImpl()
        {
        }

        public void OnAddInsUpdate(ref Array custom)
        {
        }

        public void OnBeginShutdown(ref Array custom)
        {
        }

        public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            Application = (Microsoft.Office.Interop.Excel.Application)application;
            COMAddIn = (Microsoft.Office.Core.COMAddIn)addInInst;
        }

        public void OnDisconnection(Extensibility.ext_DisconnectMode removeMode, ref Array custom)
        {
        }

        public void OnStartupComplete(ref Array custom)
        {
        }

        #region COM Registration

        [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type type)
        {
            type.RegisterCOMAddin(OfficeApp.Excel, "Topic Bus Subscriber", "Topic Bus Subscriber", LoadBehaviour.Connected | LoadBehaviour.Bootload, true);
            type.RegisterAutomationAddin();
        }

        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type type)
        {
            type.UnregisterAutomationAddin();
            type.UnregisterCOMAddin(OfficeApp.Excel);
        }

        #endregion

        public object TopicSubscribe(string feed, string topic, string fieldName, object defaultValue, object host, object port)
        {
            if (Application == null)
                return ExcelUtils.XlErrValue;

            return Application.WorksheetFunction.RTD(Subscriber.ProgId, Type.Missing, feed, topic, fieldName, defaultValue, host, port);
        }
    }
}
